/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;
/**
 * 说明：
 * 添加员工界面
 * @Author：
 * @Date：2012-03-22
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TDept;
import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.bean.TRole;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.IDNameBean;
import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.DataPackageComponent;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJPasswordFieldComponent;
import com.ruipengkj.component.JLabelJTextAreaComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.service.TDeptService;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TRoleService;

public class DataEmployeesAddOrModifyDialog extends IDialog implements ActionListener{

	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent EmployeeSn;//员工号
	private JLabelJTextFieldComponent Name;//员工姓名
	private JLabelJTextFieldComponent UserName;// 员工用户名 CHAR(15)
	
	
	private JLabelJComboBoxComponent Sex;//员工性别   TINYINT1为男 2为女
	private JLabelJComboBoxComponent Edulevel;//文化程度TINYINT 1为未知 2为小学 2为中学 3为高中 4为大学 5为硕士 6为博士
	private DataPackageComponent BirthDate;//出生日期
	
	private JLabelJTextFieldComponent Mobile;//手机
	private JLabelJTextFieldComponent Phone;//电话
	private JLabelJTextFieldComponent NationalID;//身份证号
	
	private JLabelJTextFieldComponent ZipCode;// 邮编 CHAR(6)
	private JLabelJTextFieldComponent Salary;//标准工资
	private JLabelJTextFieldComponent Allowance;//津贴
	
	private DataPackageComponent EmployStart;//合同开始时间
	private DataPackageComponent EmployEnd;//合同到期时间
	private JLabelJComboBoxComponent IsValid;//是否有效
	
	private JLabelJTextFieldComponent Job;//员工职位
	private JLabelJComboBoxComponent TDeptBox;//所属部门
	private JLabelJComboBoxComponent Role;//所属角色
	
	private JLabelJTextAreaComponent Address;//住址
	
	private JLabelJTextAreaComponent Remark;//备注
	
	private JLabelJPasswordFieldComponent password;//密码
	
	private JButton sureButton;
	private JButton cancelButton;
	private TEmployeeService temployeeService;//员工操作对象
	private TDeptService tDeptService;//部门操作对象
	private TRoleService tRoleService;//所属角色
	private List<TDept> tDeptList=null;
	private TEmployee employee=null;//员工
	public boolean isSuccess=false;
	public DataEmployeesAddOrModifyDialog(JDialog jf,String title,boolean b) {
		super(jf, title, b);
		temployeeService=BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
		tDeptService=BuildSpringApplication.getInstance().getTDeptServiceImpl();
		tRoleService=BuildSpringApplication.getInstance().getTRoleServiceImpl();
		this.setSize(880,500);
		this.setLocationRelativeTo(null);
		this.initComponents();
		this.initListener();
	}
	
	private void initComponents() {
		JPanel main_jp = new BorderJPanel();
		BoxLayout boxLayout=new BoxLayout(main_jp, BoxLayout.Y_AXIS);
		main_jp.setLayout(boxLayout);
		main_jp.setBackground(Util.PANEL_COLOR);
		
		FlowLayout flowLayout=new FlowLayout(FlowLayout.LEFT);
		JPanel jp1=new JPanel(flowLayout);
		jp1.setOpaque(false);
		EmployeeSn = new JLabelJTextFieldComponent("    员 工 号：", 30);
		UserName = new JLabelJTextFieldComponent("*", "用 户 名：", 30);
		Name = new JLabelJTextFieldComponent("*", "员工姓名：", 30);
		jp1.add(EmployeeSn);
		jp1.add(UserName);
		jp1.add(Name);
		
		JPanel jp2=new JPanel(flowLayout);
		jp2.setOpaque(false);
		Sex = new JLabelJComboBoxComponent("    性    别：", ApplicationContext.SEX_MAP(),187);
		Edulevel= new JLabelJComboBoxComponent(" 文化程度：",ApplicationContext.EDULEVEL_MAP(),187);
		BirthDate = new DataPackageComponent(" 出生日期：", 30, "yyyy-MM-dd");
		jp2.add(Sex);
		jp2.add(Edulevel);
		jp2.add(BirthDate);
		
		JPanel jp3=new JPanel(flowLayout);
		jp3.setOpaque(false);
		Mobile = new JLabelJTextFieldComponent("  *", "手机号码：", 30);
		Phone = new JLabelJTextFieldComponent(" 电    话：", 30);
		NationalID = new JLabelJTextFieldComponent("*", "身份证号：", 30);
		jp3.add(Mobile);
		jp3.add(Phone);
		jp3.add(NationalID);
		
		JPanel jp4=new JPanel(flowLayout);
		jp4.setOpaque(false);
		ZipCode= new JLabelJTextFieldComponent("    邮    编：", 30);
		Salary= new JLabelJTextFieldComponent("*", "标准工资：", 30);
		Allowance= new JLabelJTextFieldComponent("*", "津    贴：", 30);
		jp4.add(ZipCode);
		jp4.add(Salary);
		jp4.add(Allowance);
		
		JPanel jp5=new JPanel(flowLayout);
		jp5.setOpaque(false);
		Job = new JLabelJTextFieldComponent("    职    位：", 30);
		TDeptBox=new JLabelJComboBoxComponent("*", "所属部门：",new String[]{"请选择部门"},187);
		Role=new JLabelJComboBoxComponent("*", "所属角色：",new String[]{},187);
		Role.addElement(new IDNameBean("0", "普通员工"));
		jp5.add(Job);
		jp5.add(TDeptBox);
		jp5.add(Role);
		
		JPanel jp6=new JPanel(flowLayout);
		jp6.setOpaque(false);
		EmployStart= new DataPackageComponent("合同开始时间：", 30);
		EmployEnd= new DataPackageComponent("合同到期时间：", 30);
		IsValid=new JLabelJComboBoxComponent("是否有效：", new String[]{"有","无"},188);
		jp6.add(EmployStart);
		jp6.add(EmployEnd);
		jp6.add(IsValid);
		
		
		Address = new JLabelJTextAreaComponent("     地    址：", 30,2);
		Remark= new JLabelJTextAreaComponent("     备    注：", 30,2);
		
		JPanel jp7=new JPanel(flowLayout);
		jp7.setOpaque(false);
		password=new JLabelJPasswordFieldComponent("  *", "默认密码：", 30);
//		QQ=new JLabelJTextFieldComponent("    Q    Q：", 30);
		jp7.add(password);
//		jp7.add(QQ);
		main_jp.add(jp1);
		main_jp.add(jp2);
		main_jp.add(jp3);
		main_jp.add(jp4);
		main_jp.add(jp5);
		main_jp.add(jp6);
		main_jp.add(jp7);
		main_jp.add(Address);
		main_jp.add(Remark);
		
//		EmployeeSn.getText().setText(UUID.GenUUID15());
		EmployeeSn.getText().setEditable(false);
		
		JPanel down_jp=uiFactory.createFlowJPanel();
		sureButton=new RPJButtonWhite("保存(Ctrl+S)");
		cancelButton=new RPJButtonWhite("取消(Ctrl+Q)");
		down_jp.add(sureButton);
		down_jp.add(cancelButton);
		down_jp.setBackground(Util.PANEL_COLOR);
		
		main_jp.add(down_jp);
		this.add(main_jp,BorderLayout.CENTER);
//		this.add(down_jp,BorderLayout.SOUTH);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
	}
	
	private void initListener(){
		sureButton.addActionListener(this);
		sureButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		cancelButton.addActionListener(this);
		cancelButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==sureButton){//确定按钮
			String EmployeeSnStr=EmployeeSn.getText().getText().trim();//员工号
			String NameStr=Name.getText().getText().trim();//员工姓名
			String UserNameStr=UserName.getText().getText().trim();// 员工用户名 CHAR(15)
			String SexStr=Sex.getBox().getSelectedItem().toString();//员工性别   TINYINT1为男 2为女
			String EdulevelStr=Edulevel.getBox().getSelectedItem().toString();//文化程度TINYINT 1为未知 2为小学 2为中学 3为高中 4为大学 5为硕士 6为博士
			Date BirthDateStr=BirthDate.getDate();//出生日期
			String MobileStr=Mobile.getText().getText().trim();//手机
			String PhoneStr=Phone.getText().getText().trim();//电话
			String NationalIDStr=NationalID.getText().getText().trim();//身份证号
			String ZipCodeStr=ZipCode.getText().getText().trim();// 邮编 CHAR(6)
			String SalaryStr=Salary.getText().getText().trim();//标准工资
			String AllowanceStr=Allowance.getText().getText().trim();//津贴
			Date EmployStartStr=EmployStart.getDate();//合同开始时间
			Date EmployEndStr=EmployEnd.getDate();//合同到期时间
			String IsValidStr=IsValid.getBox().getSelectedItem().toString();//是否有效
			String JobStr=Job.getText().getText().trim();//员工职位
			String TDeptStr=TDeptBox.getBox().getSelectedItem().toString();//所属部门
			String AddressStr=Address.getArea().getText().trim();//住址
			String RemarkStr=Remark.getArea().getText().trim();//备注
			String passwordStr=password.getText().getText().trim();//默认密码
//			String emealStr=Emeal.getText().getText().trim();
			if(BirthDateStr==null){
				BirthDateStr=new Date();
			}
			if(EmployStartStr==null){
				EmployStartStr=new Date();
			}
			if(EmployEndStr==null){
				EmployEndStr=new Date();
			}
			if(UserNameStr.equals("")||UserNameStr.length()>15){
				JOptionPane.showMessageDialog(null, "用户名不能为空，且不能大于15个字");
				UserName.requestFocus();
				return;
			}
			if(NameStr.equals("")||NameStr.length()>20){
				JOptionPane.showMessageDialog(null, "名称不能为空，且不能大于20个字");
				Name.requestFocus();
				return;
			}
			if(MobileStr.equals("")||!MatcherFormatUtil.checkMobileScheme(MobileStr)){
				JOptionPane.showMessageDialog(null, "手机号码不能为空，请输入正确的手机号码");
				Mobile.getText().requestFocus();
				return ;
			}
			if(PhoneStr.length()>20){
				JOptionPane.showMessageDialog(null, "电话号码不能大于30个字");
				Phone.requestFocus();
				return;
			}
			
			if(NationalIDStr.equals("")||NationalIDStr.length()>32){
				JOptionPane.showMessageDialog(null, "身份证号码不能为空，且不能大于32个字");
				NationalID.requestFocus();
				return;
			}
			if(ZipCodeStr.length()>6){
				JOptionPane.showMessageDialog(null, "邮编不能大于6个字");
				ZipCode.requestFocus();
				return;
			}
			if(!SalaryStr.equals("")&&!MatcherFormatUtil.MatcherPriceScheme(SalaryStr)){
				JOptionPane.showMessageDialog(null, "标准工资小数点左边不能超过10位，右边不能超过2位");
				Salary.requestFocus();
				return;
			}else if(SalaryStr.equals("")){
				SalaryStr="0.00";
			}
			if(!AllowanceStr.equals("")&&!MatcherFormatUtil.MatcherPriceScheme(AllowanceStr)){
				JOptionPane.showMessageDialog(null, "津贴小数点左边不能超过10位，右边不能超过2位");
				Allowance.requestFocus();
				return;
			}else if(AllowanceStr.equals("")){
				AllowanceStr="0.00";
			}
			if(JobStr.length()>30){
				JOptionPane.showMessageDialog(null, "员工职位不能大于30个字");
				Job.requestFocus();
				return;
			}
			
			if(AddressStr.length()>128){
				JOptionPane.showMessageDialog(null, "住址不能大于128个字");
				Address.requestFocus();
				return;
			}
			if(RemarkStr.length()>512){
				JOptionPane.showMessageDialog(null, "备注不能大于512个字");
				Remark.requestFocus();
				return;
			}
			if(passwordStr.equals("")||passwordStr.length()<6||passwordStr.length()>20){
				JOptionPane.showMessageDialog(null, "默认密码不能为空，不能小于6位且不能大于20位");
				password.requestFocus();
				return;
			}
			
			boolean isOpLog=false;
			if(TDeptStr.equals("请选择部门")){
				JOptionPane.showMessageDialog(null, "请选择员工所属部门");
				return;
			}
			try {
				
				if(employee==null){
					if(temployeeService.getTEmployeeByUserName(UserNameStr)!=null){
						JOptionPane.showMessageDialog(null, "当前用户名已经存在，请重新输入");
						UserName.requestFocus();
						return;
					}
					
					List<TEmployee> list = temployeeService.findByNameService(NameStr);
					if (list != null && list.size() != 0) {
						if (Util.showConfirmDialog("存在相同名字的员工，确定添加吗？") != 0)
							return;
					}
					
					employee=new TEmployee();
					employee.setEmployeeID(UUID.GenUUID15());//编号
					isOpLog=true;
				}
				employee.setEmployeeSn(EmployeeSnStr);//员工号
				employee.setName(NameStr);//姓名
				employee.setUserName(UserNameStr);//用户名
				employee.setPassword(passwordStr);//密码
				employee.setSex((Byte)Sex.getKeyByVaule(SexStr));//性别
				employee.setEdulevel((Byte)Edulevel.getKeyByVaule(EdulevelStr));//文化程度TINYINT 1为未知 2为小学 2为中学 3为高中 4为大学 5为硕士 6为博士
				employee.setBirthDate(BirthDateStr);//出生日期
				employee.setMobile(MobileStr);//手机
				employee.setPhone(PhoneStr);//电话
				employee.setNationalID(NationalIDStr);//身份证号
				employee.setZipCode(ZipCodeStr);// 邮编 CHAR(6)
				employee.setSalary(Double.parseDouble(SalaryStr+""));//标准工资
				employee.setAllowance(Double.parseDouble(AllowanceStr+""));//津贴
				employee.setEmployStart(EmployStartStr);//合同开始时间
				employee.setEmployEnd(EmployEndStr);//合同到期时间
				if(IsValidStr.equals("有")){
					employee.setIsValid(true);
				}else{
					employee.setIsValid(false);
				}
				employee.setJob(JobStr);//员工职位
				
				employee.setOperator(ApplicationContext.OPERATOR_ID);//创建人
				employee.setAddress(AddressStr);//住址
				employee.setRemark(RemarkStr);//备注
				employee.setTDept(this.getTDept(TDeptStr));//所属部门
				if(Role.getBox().getSelectedIndex()!=0){
					IDNameBean bean=(IDNameBean)Role.getBox().getSelectedItem();//权限
					employee.setTRole(new TRole(bean.getStrId()));
				}
				
				temployeeService.saveOrUpdateService(employee);
				this.isSuccess=true;
				if(isOpLog){
					BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("添加员工信息");
				}else{
					BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("修改员工信息");	
				}
				JOptionPane.showMessageDialog(null, "操作成功");
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(null, "操作失败");
			}
			this.dispose();
		}else if(e.getSource()==cancelButton){//取消按钮
			this.dispose();
		}
		super.actionPerformed(e);
	}
	private String deptName;
	public void showDialog(TEmployee employee, String deptName) {
		this.isSuccess=false;
		if(employee!=null){
			this.employee=employee;
			EmployeeSn.getText().setText(employee.getEmployeeSn());//员工号
			Name.getText().setText(employee.getName());//员工姓名
			UserName.getText().setText(employee.getUserName());// 员工用户名 CHAR(15)
			UserName.getText().setEditable(false);
			password.getText().setText(employee.getPassword());//密码
			Sex.getBox().setSelectedItem(ApplicationContext.SEX_MAP().get(employee.getSex()));//员工性别   TINYINT1为男 2为女
			Edulevel.getBox().setSelectedItem(ApplicationContext.EDULEVEL_MAP().get(employee.getEdulevel()));//文化程度TINYINT 1为未知 2为小学 2为中学 3为高中 4为大学 5为硕士 6为博士
			BirthDate.setDate(employee.getBirthDate());//出生日期
			Mobile.getText().setText(employee.getMobile());//手机
			Phone.getText().setText(employee.getPhone());//电话
			NationalID.getText().setText(employee.getNationalID());//身份证号
			ZipCode.getText().setText(employee.getZipCode());// 邮编 CHAR(6)
			Salary.getText().setText(employee.getSalary()+"");//标准工资
			Allowance.getText().setText(employee.getAllowance()+"");//津贴
			EmployStart.setDate(employee.getEmployStart());//合同开始时间
			EmployEnd.setDate(employee.getEmployEnd());//合同到期时间
			if(employee.isIsValid()){
				IsValid.getBox().setSelectedItem("有");//是否有效
			}else{
				IsValid.getBox().setSelectedItem("无");//是否有效
			}
			Job.getText().setText(employee.getJob());//员工职位
			Address.getArea().setText(employee.getAddress());//住址
			Remark.getArea().setText(employee.getRemark());//备注
		}
		queryThread.start();
		if (deptName != null) {
			this.deptName = deptName;
//			TDeptBox.getBox().setSelectedItem(deptName);
		}
		this.setVisible(true);
	}
	
	private Thread queryThread=new Thread(){
		public void run(){
			//获取员工号
			try {
				if (EmployeeSn.getText().getText().equals("")) {
					String sn = temployeeService.getTEmployeeSn();
					EmployeeSn.getText().setText(sn);
//					System.out.println(sn);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			try {
				tDeptList=tDeptService.findService(null);
				if(tDeptList!=null&&tDeptList.size()!=0){
					boolean isSelect = false;
					for(int i=0;i<tDeptList.size();i++){
						TDeptBox.addElement(tDeptList.get(i).getName());
						if (!isSelect && employee != null) {
							TDept dep=employee.getTDept();
							if(dep!=null&&dep.getName().equals(tDeptList.get(i).getName())){
								TDeptBox.getBox().setSelectedIndex(i+1);
								isSelect = true;
							}
						}
					}
					if (deptName!= null && employee == null){
						TDeptBox.getBox().setSelectedItem(deptName);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			//所属角色
			try {
				List<TRole> list=tRoleService.findService(null);
				if(list!=null&&list.size()!=0){
					for(int i=0;i<list.size();i++){
						TRole emp=list.get(i);
						if(emp.getName().equals("超级管理员")){
							continue;
						}
						Role.addElement(new IDNameBean(emp.getRoleID(), emp.getName()));
						if(employee!=null){
							TRole role=employee.getTRole();
							if(role!=null&&role.getRoleID()!=null){
								if(emp.getRoleID().equals(role.getRoleID())){
									Role.getBox().setSelectedIndex(i);//角色
								}
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	private TDept getTDept(String name){
		if(tDeptList!=null&&tDeptList.size()!=0){
			for(int i=0;i<tDeptList.size();i++){
				TDept tDept=tDeptList.get(i);
				if(tDept.getName().equals(name)){
					return tDept;
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		DataEmployeesAddOrModifyDialog dialog = new DataEmployeesAddOrModifyDialog(null, "添加员工", true);
		dialog.setVisible(true);
	}
}
